/// <reference types="@dcloudio/types" />

/// ！！！如非必要请勿修改该页面的函数逻辑！！！
///

import { message } from '@/common/message';
import { getToken } from '@/common/storage';

const Home_Path: string = 'pages/home/index';

export const TABBAR_ROUTES = [
  `/${Home_Path}`,
  '/pages/aunt/index',
  '/pages/customer/index',
];

export const goback = (origin?: string) => {
  origin
    = origin && typeof origin === 'string' && origin.includes('pages')
      ? origin.startsWith('/')
        ? origin
        : `/${origin}`
      : undefined;

  if (origin) {
    if (TABBAR_ROUTES.includes(origin)) {
      return uni.switchTab({ url: origin });
    }
    return uni.reLaunch({ url: origin });
  }

  uni.navigateBack().catch(() => {
    uni.switchTab({
      url: `/${Home_Path}`,
    });
  })
}

const BLACK_ROUTES: string[] = [];

/**
 * @param {string} page
 * @returns {{ path: string, type: string }}
 */
const handlePath = (
  page: string,
): {
  path: string
  type: 'navigateTo' | 'switchTab' | 'reLaunch' | 'redirectTo'
} => {
  if (TABBAR_ROUTES.includes(page)) {
    return { path: page, type: 'switchTab' };
  }
  else {
    if (!getToken() && BLACK_ROUTES.includes(page)) {
      const pages = getCurrentPages();
      let path = `/${Home_Path}` // 登录后的返回页面
      if (pages && pages.length > 0) {
        const curPage: Record<string, any> = pages[pages.length - 1];
        if (curPage.route) {
          path
            = curPage?.$page?.route
              || `${curPage.route}${curPage.options ? `?${Object.entries(curPage.options || {}).reduce((acc: string, [key, value]) => `${acc}${key}=${value}&`, '')}` : ''}`
        }
      }
      return {
        path: `/pages/user/login/index?path=${encodeURIComponent(path)}`,
        type: 'reLaunch',
      };
    }

    if (page.includes('/pages/user/login/index')) {
      const pages = getCurrentPages();
      let path = `/${Home_Path}` // 登录后的返回页面
      if (pages && pages.length > 0) {
        const curPage: Record<string, any> = pages[pages.length - 1];
        if (curPage.route) {
          path
            = curPage?.$page?.route
              || `${curPage.route}${curPage.options ? `?${Object.entries(curPage.options || {}).reduce((acc: string, [key, value]) => `${acc}${key}=${value}&`, '')}` : ''}`
        }
      }
      return {
        path: `/pages/user/login/index?path=${encodeURIComponent(path)}`,
        type: 'reLaunch',
      };
    }

    return { path: page, type: 'navigateTo' };
  }
};
type ToRoute = (params: UniApp.NavigateToOptions) => void

/// 在限制页面中使用goToPage方法, 而在非限制页面中使用this.$route
/**
 *
 * @param {string} page
 * @returns {void}
 */
export const goToPage = (
  page: string,
  query?: string | Record<string, string | number>,
): void => {
  if (!page || page.trim() === '') {
    message.info('敬请期待');
    return
  }
  const result = handlePath(page);

  query = query
    ? `?${
      typeof query === 'string'
        ? query
        : Object.keys(query)
          .map(
            (key) =>
              `${key}=${(query as Record<string, string | number>)[key]}`,
          )
          .join('&')
    }`
    : ''

  if (uni[result.type]) {
    return (uni[result.type] as unknown as ToRoute)({
      url: result.path + query,
      success: (e) => {
        if (import.meta.env.VITE_USER_NODE_ENV === 'development') {
          console.log(
            `%c${e.errMsg}%c`,
            'background: #00cc09; color: #fff; border-radius: 3px 0 0 3px;padding:2px 8px',
            page,
          );
        }
      },
      fail: (e) => {
        console.log(
          `%c${e.errMsg}%c`,
          'background: rgb(233, 51, 35); color: #fff; border-radius: 3px 0 0 3px;padding:2px 5px',
          page,
        );
        uni.showModal({
          title: '提示',
          content: e.errMsg.includes('url') ? '请检查路径是否正确' : e.errMsg,
          showCancel: false,
        });
      },
    });
  }
};
